<template>
  <div class="app-container">
    <el-card class="box-card">
      <!-- <h4>{{ $t("新增规则") }}</h4> -->
      <div slot="header" class="clearfix">
        <span>{{ $t("新增规则") }}</span>
      </div>
      <el-form :model="dataForm" status-icon label-position="left" style="width: 600px">
        <el-form-item prop="useRange">
          <div>
            {{ $t('规则名称') }}
            <el-input v-model="dataForm.name" clearable style="width: 250px" />
          </div>
        </el-form-item>

        <span>{{ $t("赠送方式") }}</span>
        <el-form-item prop="useRange">
          <div>
            <el-radio v-model="dataForm.giveMethod" :label="1" :disabled="this.ruleId != undefined">{{ $t("邀请注册即送") }}
            </el-radio>
            <el-radio v-model="dataForm.giveMethod" :label="2" :disabled="this.ruleId != undefined">{{ $t("邀请注册激活即送") }}
            </el-radio>
            <el-radio v-model="dataForm.giveMethod" :label="3" :disabled="this.ruleId != undefined">{{ $t("激活并消费后赠送") }}
            </el-radio>
          </div>
        </el-form-item>
        <span style="line-height: 30px">{{ $t("受益方") }}</span>
        <el-form-item prop="beneficiary">
          <div>
            <el-radio v-model="dataForm.beneficiary" :label="1" :disabled="this.ruleId != undefined">{{ $t("邀请人") }}
            </el-radio>
            <el-radio v-model="dataForm.beneficiary" :label="2" :disabled="this.ruleId != undefined">{{ $t("被邀请人") }}
            </el-radio>
          </div>
        </el-form-item>
        <span>{{ $t("赠送条件") }}</span>
        <el-form-item prop="useRange">
          <div>
            <div>{{ $t("邀请量") }}</div>

            <el-link type="primary" @click="Visible" icon="el-icon-plus">{{ $t('邀请规则') }}
            </el-link>
          </div>
        </el-form-item>
        <el-table border :data="this.ruleList">
          <el-table-column :label='$t("数量")' align="center" prop="perNum"></el-table-column>
          <el-table-column :label='$t("赠送优惠券")' prop="couponName" align="center"></el-table-column>
          <el-table-column :label='$t("赠送积分")' prop="presentPoints" align="center">

          </el-table-column>
          <el-table-column align="center" :label="$t('Operate')" width="80" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button type="danger" size="mini" @click="handleDelete(scope.$index, scope.row)">{{ $t('Delete') }}
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <span style="line-height: 30px">{{ $t("有效时间") }}</span>
        <el-form-item prop="dateRange">
          <div>
            <el-date-picker v-model="dataForm.startDate" class="filter-item" :editable="false" :clearable="true"
              :placeholder="$t('Start_time')" format="yyyy 年 MM 月 dd 日" value-format="yyyy-MM-dd"></el-date-picker>
            {{ $t('到') }}
            <el-date-picker v-model="dataForm.endDate" class="filter-item" :editable="false" :clearable="true"
              :placeholder="$t('End_time')" format="yyyy 年 MM 月 dd 日" value-format="yyyy-MM-dd"></el-date-picker>
          </div>
        </el-form-item>

      </el-form>

      <el-dialog :visible.sync="outerVisible">

        <el-dialog width="50%" :title='$t("选择优惠券")' :visible.sync="innerVisible" append-to-body>
          <el-table ref="multipleTable" :data="tableData" border tooltip-effect="dark" style="width: 100%"
            @selection-change="handleSelectionChange" :row-key="(row) => row.id">
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column :label='$t("序号")' width="200">
              <template slot-scope="scope">{{ scope.row.id }}</template>
            </el-table-column>
            <el-table-column prop="strategyName" :label='$t("优惠卷策略名称")' show-overflow-tooltip />
            <el-table-column prop="couponName" :label='$t("优惠卷名称")' show-overflow-tooltip />
            <el-table-column :label='$t("优惠卷类型")' width="140">
              <template slot-scope="scope">{{ scope.row.discountType == 1 ? $t('满减') : $t('折扣') }}</template>
            </el-table-column>

            <el-table-column :label='$t("优惠率")' width="100" >
              <template slot-scope="{row}">
                <el-tag effect="plain1" type="success"> {{ row.discountType == 1 ? row.discount + '$' : +row.discountRate + '%' }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column :label='$t("最低消费")' width="120">
              <template slot-scope="scope">{{ scope.row.min  + '$'}}</template>
            </el-table-column>
          </el-table>
          <div style="margin-top: 20px">
            <el-button icon="el-icon-success" @click="Selection()">{{ $t('确定') }}
            </el-button>
            <el-button icon="el-icon-error" @click="toggleSelection()">{{ $t("取消选择") }}</el-button>
          </div>
        </el-dialog>
        <el-dialog width="50%" :title='$t("积分设置")' :visible.sync="innerVisibles" append-to-body
          :close-on-click-modal="false">
          <div>

            <el-input v-model.number="presentPoints" type="number" style="width: 200px" min="1"
                      onkeyup="if(value===''){value=0};value=value.replace(/[^0-9]/g,'');if(value>=9999){value=9999};if(String(value)==='0'){value=0}" />
            {{ $t('积分') }}
          </div>
          <div style="margin-top: 20px">
            <el-button plain1 icon="el-icon-success" @click="PionSelections()">{{ $t("确认") }}</el-button>
            <el-button plain1 icon="el-icon-error" @click="toggleSelections()">{{ $t("取消选择") }}</el-button>
          </div>
        </el-dialog>
        <div>
          <div>
            <div class="Tips-title">
              <div style="margin-right: 30px">{{ $t("活动规则配置") }}</div>
              <el-button type="primary" plain1 icon="el-icon-circle-plus" @click="addRule">{{ $t("添加条目") }}</el-button>
            </div>
            <div class="Tips-title" v-for="(res, i) in dataForm.adminRewardConfigDtos" :key="i">

              <div>
                <div class="Tips-coupon">
                  <div style="margin-left: 40px"><el-tag type="warning">{{ $t("赠送礼品") }} <i class="el-icon-present"></i> </el-tag></div>
                  <div style="margin-left: 40px">
                    <el-link type="primary" @click="CouPonVisible(res, i)" icon="el-icon-plus">{{ $t('优惠劵') }}
                    </el-link>
                    <div v-for="(item, index) in res.presentCouponId" :key="index">{{ item.couponName }}</div>
                  </div>
                  <div style="margin-left: 40px">
                    <el-link type="primary" @click="PionVisibles(i)" icon="el-icon-plus">{{ $t('积分') }}
                    </el-link>
                    <div>{{ res.presentPoints }}</div>
                  </div>
                  <div style="margin-left: 20px">
                    {{ $t('邀请人数累计') }}
                    <el-input v-model.number="res.perNum" type="number" style="width: 100px" min="0"
                              onkeyup="if(value===''){value=0};value=value.replace(/[^0-9]/g,'');if(value>=9999){value=9999};if(String(value)==='0'){value=0}" />
                  </div>
                  <div style="margin-left: 40px" @click="deleteConfig(i)">
                    <el-button plain1 type="danger" icon="el-icon-delete" circle></el-button>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <el-button plain1 icon="el-icon-error"  @click="confingConfirm">{{ $t('取消') }}</el-button>
          <el-button plain1 icon="el-icon-success" type="primary" @click="confingConfirm">{{ $t("确定") }}</el-button>
        </div>
      </el-dialog>

      <div class="op-container">
        <el-button plain1 type="primary" icon="el-icon-s-promotion" v-if="status != 2" @click="updateData">{{
          $t('Confirm')
        }}
        </el-button>
        <!--        <el-button type="primary" @click="handleBack">{{$t("确定并立即生效")}}</el-button>-->
        <el-button plain1 icon="el-icon-error" @click="handleBack">{{ $t("取消") }}</el-button>
      </div>
    </el-card>

    <el-card class="box-card" style="margin-top:20px;" v-if="this.ruleId">
      <div slot="header" class="clearfix">
        <span>{{ $t('统计周期') }}</span>
      </div>
      <el-row style="margin-bottom: 20px;">
        <el-col :span="8" align="center">
          <el-row>
            <span style="font-size: 30px;color: red;">{{ this.dataTimeTitle.beInvitedNum }}</span>
          </el-row>
          <el-row>
            {{ $t('送出优惠券数量') }}
          </el-row>
        </el-col>
        <el-col :span="8" align="center">
          <el-row>
            <span style="font-size: 30px;color: red;">{{ this.dataTimeTitle.counpNum }}</span>
          </el-row>
          <el-row>
            {{ $t('邀请人数') }}
          </el-row>
        </el-col>
        <el-col :span="8" align="center">
          <el-row>
            <span style="font-size: 30px;color: red;">{{ this.dataTimeTitle.invitationNum }}</span>
          </el-row>
          <el-row>
            {{ $t('被邀请人数') }}
          </el-row>
        </el-col>
      </el-row>

      <el-table border :data="this.dataTimeLineList">
        <el-table-column :label='$t("邀请人账号")' align="center" prop="invitationAccount"></el-table-column>
        <el-table-column :label='$t("邀请人昵称")' align="center" prop="invitationNikeName"></el-table-column>
        <el-table-column :label='$t("邀请日期")' align="center" prop="invitationDate"></el-table-column>
        <el-table-column :label='$t("累计积分")' align="center" prop="presentPoints"></el-table-column>
        <el-table-column :label='$t("赠送优惠券码")' align="center" prop="counpCode"></el-table-column>
        <el-table-column :label='$t("赠送优惠券名称")' align="center" prop="counpName"></el-table-column>
        <el-table-column :label='$t("被邀请人账号")' align="center" prop="beInvitedAccount"></el-table-column>
        <el-table-column :label='$t("被邀请人昵称")' align="center" prop="beInvitedNikeName"></el-table-column>
        <el-table-column :label='$t("被邀请人注册日期")' align="center" prop="registerDate"></el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" :page.sync="dataQuery.page" :limit.sync="dataQuery.limit"
        @pagination="getList" />


    </el-card>
  </div>
</template>

<script>
import { listCoupon } from '../../api/coupon'
import { addReward, detailReward, updateReward, getPeriodStatistics } from '../../api/distribution'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
import {ruleConfigCoupons} from '@/api/couponStrategy'

export default {
  name: 'RuleConfig',
  components: { Pagination },
  data() {
    return {
      status: undefined,
      value1: '',
      outerVisible: false,
      innerVisible: false,
      innerVisibles: false,
      configPion: '',
      presentPoints: undefined,
      selectConfigIndex: undefined,
      ruleId: undefined,
      dataForm: {
        id: undefined,
        giveMethod: 1,
        startDate: undefined,
        endDate: undefined,
        beneficiary: undefined,
        adminRewardConfigDtos: [
          {
            perNum: 0,
            presentCouponId: [],
            couponName: undefined,
            presentPoints: undefined
          }
        ]
      },
      dataQuery: {
        limit: 10,
        page: 1,
        ruleId: undefined,
      },
      dataTimeTitle: {
        beInvitedNum: undefined,
        counpNum: undefined,
        invitationNum: undefined,
      },
      currMultipleTable: [],
      total: undefined,
      dataTimeLineList: [],
      ruleList: [],
      multipleSelection: [],//选中的优惠卷
      index: 0,
      tableData: [],
      list: [
        //  {name:'111',total:1,discountType:1,}
      ]
    }
  },
  updated() {

  },
  created() {
    this.ruleId = this.$route.query.id
    this.status = this.$route.query.status
    if (this.ruleId) {
      detailReward(this.ruleId).then(response => {
        this.dataForm = response.data.data
        this.ruleList = this.dataForm.adminRewardConfigDtos
        this.dataForm.adminRewardConfigDtos.splice(this.dataForm.adminRewardConfigDtos.length)
      })
      this.dataQuery.ruleId = this.ruleId;
      this.getList();
    }
    this.getCouponList()
  },
  methods: {
    getList() {
      getPeriodStatistics(this.dataQuery).then(response => {
        const res = response.data.data;
        const { beInvitedNum, counpNum, invitationNum, periodStatisticsList } = res;
        this.dataTimeTitle.beInvitedNum = beInvitedNum;
        this.dataTimeTitle.counpNum = counpNum;
        this.dataTimeTitle.invitationNum = invitationNum;
        this.dataTimeLineList = periodStatisticsList.content;
        this.total = periodStatisticsList.totalElements;
      })
    },
    confingConfirm() {
      this.outerVisible = false
      this.dataForm.adminRewardConfigDtos.splice(this.dataForm.adminRewardConfigDtos.length)
      this.ruleList = this.dataForm.adminRewardConfigDtos
    },
    // 确认选择
    Selection() {
      this.dataForm.adminRewardConfigDtos[this.index].presentCouponId = this.multipleSelection
      console.log('dian'+JSON.stringify(this.dataForm.adminRewardConfigDtos[this.index].presentCouponId))
      var couponName = '';
      for (let i = 0; i < this.multipleSelection.length; i++) {
        couponName += this.multipleSelection[i].couponName + ","
      }
      this.dataForm.adminRewardConfigDtos[this.index].couponName = couponName

      this.multipleSelection = []
      this.$refs.multipleTable.clearSelection();
      this.innerVisible = false
    },
    CouPonVisible(res, i) {
      this.innerVisible = true
      this.index = i;
      console.log(res);
      const { presentCouponId } = res;
      if (presentCouponId.length) {
        this.currMultipleTable = presentCouponId;
        this.currMultipleTable.forEach(item => {
          this.$refs.multipleTable.toggleRowSelection(item, true);
        })
      } else {
        this.currMultipleTable = [];
      }
    },
    handleBack() {
      this.$router.push({ path: '/Distribution/reward' })
    },
    updateData() {
      var type = this.$route.query.type;
      /*const adminRewardBoolean = this.dataForm.adminRewardConfigDtos.some(item => {
        return !item.presentPoints || item.presentCouponId.length == 0 || item.perNum == 0;
      })
      if (adminRewardBoolean) {
        return this.$message.error(this.$t('邀请量不能为空'));
      }*/
      if (type == 1) {
        addReward(this.dataForm).then(response => {
          this.$notify.success({
            title: this.$t('Success!'),
            message: this.$t('添加奖励规则成功')
          })

          this.$router.push({ path: '/Distribution/reward' })
        }).catch(response => {
          this.$notify.error({
            title: this.$t('Failed'),
            message: this.$t(response.data.errmsg)
          })
        })
      } else {
        updateReward(this.dataForm).then(response => {
          this.$notify.success({
            title: this.$t('Success!'),
            message: this.$t('更新奖励规则成功')
          })

          this.$router.push({ path: '/Distribution/reward' })
        }).catch(response => {
          this.$notify.error({
            title: this.$t('Failed'),
            message: this.$t(response.data.errmsg)
          })
        })
      }
    },
    toggleSelections() {
      this.innerVisibles = false
    },
    PionSelections() {
      this.dataForm.adminRewardConfigDtos[this.index].presentPoints = this.presentPoints
      this.innerVisibles = false
    },
    addRule() {
      this.dataForm.adminRewardConfigDtos.push({ perNum: 0 })
      this.ruleList = this.dataForm.adminRewardConfigDtos
      console.log(this.dataForm);
    },
    PionVisibles(i) {
      this.configPion = '',
        this.selectConfigIndex = i
      this.innerVisibles = true
      this.index = i
    },
    Visible() {
      this.outerVisible = true
    },
    toggleSelection() {
      this.$refs.multipleTable.clearSelection();
      this.innerVisible = false
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
      console.log('点击选择'+JSON.stringify(val), this.$refs.multipleTable);

    },
    deleteConfig(i) {
      this.dataForm.adminRewardConfigDtos.shift()
    },
    getCouponList() {
      ruleConfigCoupons().then(res => {
        console.log('策略列表'+JSON.stringify(res))
        this.tableData = res.data.data
      })
    },
    handleDelete(data, row) {
      this.$confirm(this.$t('是否') + this.$t('删除该配置') + '?', this.$t('提示'), {
        confirmButtonText: this.$t('Confirm'),
        cancelButtonText: this.$t('Cancel'),
        type: 'warning'
      }).then(() => {
        this.ruleList.splice(data, 1)
        // this.dataForm.adminRewardConfigDtos.splice(data, 1)
        if (row.subscribeId) {
          this.subscribeVos = this.subscribeVos.filter(item => item.subscribeId != row.subscribeId)
        } else {
          this.couponDtos = this.couponDtos.filter(item => item.couponId != row.couponId)
        }
      })
    }
  }
}
</script>

<style scoped>
.Tips-title {
  display: flex;
  line-height: 30px;
  margin: 20px 0 20px 0;
}

.Tips-coupon {
  display: flex;
  line-height: 40px;
}
</style>
